package com.itstudy.controller;

import com.itstudy.pojo.Article;
import com.itstudy.pojo.PageBean;
import com.itstudy.pojo.Result;
import com.itstudy.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


@RestController
@Validated
@RequestMapping("article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

//    @GetMapping
//    public Result list() {
//        return Result.success("文章列表");
//    }

    @PostMapping
    public Result add(@RequestBody @Validated(Article.Add.class) Article article) {
        articleService.insert(article);
        return Result.success();
    }


    @GetMapping
    public Result query(Integer pageNum,Integer pageSize,
                        @RequestParam(required = false) Integer categoryId,
                        @RequestParam(required = false) String state) {
        PageBean<Article> list= articleService.pageQuery(pageNum,pageSize,categoryId,state);
        return Result.success(list);
    }

    @GetMapping("detail")
    public Result getDetail(Integer id) {
        if(id==null) {
            return Result.error("id不能为空");
        }
        Article article = articleService.getDetail(id);
        return Result.success(article);
    }

    @PutMapping
    public Result updateArticle(@RequestBody @Validated(Article.Update.class) Article article) {
        articleService.updateArticle(article);
        return Result.success();
    }

    @DeleteMapping
    public Result deleteById(Integer id) {
        int i= articleService.deleteById(id);
        if(i>0) return Result.success();
        return Result.error("无该数据，删除失败");
    }

}
